<template>
  <HeaderComponent />
  <div class="main">
    <div class="main-contan">
      <el-row :gutter="20">
        <el-col :span="16">
          <div class="left-card">
            <NewArticle :user="userinfo" />
            <el-card
              class="post-show-card"
              :body-style="{ padding: '20px 20px 0px' }"
              :key="article.id"
            >
              <div class="post-header">
                <router-link
                  :to="`/userinfo?id=${userinfo.id}`"
                  style="display: flex; align-items: flex-start"
                >
                  <img
                    :src="userinfo.avatar || '/assets/avatar/default.jpg'"
                    alt="Avatar"
                    class="user-avatar"
                  />
                  <div style="display: flex; flex-direction: column; margin-left: 15px">
                    <span class="username">{{ userinfo.username }}</span>
                    <span class="time">{{ article.time }}</span>
                  </div>
                </router-link>
                <span style="margin-left: auto" v-if="ArticleUserId == user.id">
                  <router-link :to="`/article?id=${article.id}`">
                    <el-button text>编辑</el-button></router-link
                  >
                  <el-button @click="deleteArticle" style="color: red" text
                    >删除</el-button
                  ></span
                >
              </div>
              <p class="post-content">
                <span class="post-tag">{{ article.tag }}</span>
                {{ article.content }}
              </p>
              <img
                :src="article.img"
                alt="Post Image"
                class="post-image"
                v-if="article.img"
              />
              <div class="post-stats">
                <div class="stats-left">
                  <span>{{ article.likes }}人点赞</span>
                </div>
                <div class="stats-right">
                  <span>{{ article.comments }}条评论</span>
                  <span>{{ article.shares }}次分享</span>
                </div>
              </div>
              <div class="post-comment">
                <div class="comment-input">
                  <img
                    :src="LoginUser.avatar || '/assets/avatar/default.jpg'"
                    alt="User Avatar"
                    class="user-avatar-small"
                  />
                  <el-input
                    placeholder="理性发言，友善互动"
                    v-model="comment"
                    class="comment-input-box"
                    @keyup.enter="submitComment"
                  />
                </div>
                <div class="comment-list">
                  <div
                    class="comment-item"
                    v-for="(comment, index) in commentsList"
                    :key="index"
                  >
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                      "
                    >
                      <div style="display: flex; align-items: center">
                        <router-link :to="`/userinfo?id=${comment.user_id}`">
                          <img
                            :src="comment.avatar || '/assets/avatar/default.jpg'"
                            class="user-avatar-tiny"
                          />
                        </router-link>
                        <router-link :to="`/userinfo?id=${comment.user_id}`">
                          <span class="comment-author">{{ comment.author }}</span>
                        </router-link>
                      </div>
                      <el-button
                        v-if="comment.user_id === LoginUser.id"
                        @click.stop="deleteComment(comment.id)"
                        type="danger"
                        size="small"
                        text
                      >
                        删除
                      </el-button>
                    </div>
                    <p class="comment-content">{{ comment.content }}</p>
                    <div class="comment-meta">
                      <span class="comment-time">{{ comment.time }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>

        <!-- 右侧区域 -->
        <el-col :span="8">
          <el-card class="right-card">
            <!-- 右侧内容 -->
            <div class="right-content">
              <span style="font-size: 24px; font-weight: bold">关于作者</span>
              <div class="signature-section">
                <router-link :to="`/userinfo?id=${userinfo.id}`"
                  ><img
                    :src="userinfo.avatar || '/assets/avatar/default.jpg'"
                    alt="Avatar"
                    class="signature-avatar"
                /></router-link>
                <div class="signature-info">
                  <router-link :to="`/userinfo?id=${userinfo.id}`"
                    ><span class="signature-username">{{
                      userinfo.username
                    }}</span></router-link
                  >

                  <p class="signature-text">{{ userinfo.sign || "用户未填写" }}</p>
                </div>
              </div>
              <div class="right-section">
                <el-icon class="section-icon"><User /></el-icon>
                <span>{{ userinfo.sex || "未填写" }}</span>
              </div>
              <div class="right-section">
                <el-icon class="section-icon"><Clock /></el-icon>
                <span>{{ userinfo.born || "未填写" }}</span>
              </div>
              <div class="right-section">
                <el-icon class="section-icon"><HomeFilled /></el-icon>
                <span>{{ userinfo.from || "未填写" }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import HeaderComponent from "../../components/HeaderComponent.vue";
import { Clock, User, HomeFilled } from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ref, reactive } from "vue";
import axios from "axios";
import userStore from "../../store/index";
import api from "../../utils/index.js";
const route = useRoute();
const router = useRouter();

// 用户状态管理
const userStoreInfo = userStore();
const user = userStoreInfo.getUser();

// 响应式数据
const articleId = route.query.id;
const LoginUser = reactive({});    // 登录用户信息
const article = ref({});          // 当前文章数据
const userinfo = reactive({});     // 作者信息
const commentsList = ref([]);      // 评论列表
const comment = ref("");           // 评论输入框内容
const ArticleUserId = ref("");     // 文章作者ID

// 获取文章详细信息
const info = async () => {
  try {
    // 获取文章数据
    const articleResponse = await api.get(`/articles?id=${articleId}`);
    article.value = articleResponse.data[0];

    // 获取作者信息
    const userId = article.value.user_id;
    ArticleUserId.value = userId;
    if (userId) {
      const userResponse = await api.get(`/users?id=${userId}`);
      Object.assign(userinfo, userResponse.data[0]);
      
      // 获取当前登录用户信息
      const LoginuserResponse = await api.get(`/users?id=${user.id}`);
      Object.assign(LoginUser, LoginuserResponse.data[0]);
    }

    // 获取并处理评论数据
    const commentsResponse = await api.get(`/comments?article_id=${articleId}`);
    commentsList.value = await Promise.all(
      commentsResponse.data.map(async (com) => {
        const userResponse = await api.get(`/users?id=${com.user_id}`);
        return {
          ...com,
          avatar: userResponse.data[0].avatar,
          author: userResponse.data[0].username,
        };
      })
    );
  } catch (error) {
    ElMessage.error("数据加载失败: " + error.message);
  }
};

// 提交评论
const submitComment = async () => {
  if (!comment.value.trim()) {
    ElMessage.warning("请输入评论内容");
    return;
  }
  try {
    // 提交新评论
    await api.post("/comments", {
      article_id: articleId,
      user_id: LoginUser.id,
      content: comment.value,
      time: new Date().toISOString().split("T")[0],
    });

    // 更新文章评论数
    await api.patch(`/articles/${articleId}`, {
      comments: article.value.comments + 1,
    });

    ElMessage.success("评论提交成功");
    comment.value = "";
    await info(); // 刷新数据
  } catch (error) {
    ElMessage.error("评论失败: " + error.message);
  }
};

// 删除评论
const deleteComment = async (commentId) => {
  try {
    await api.delete(`/comments/${commentId}`);
    await info(); // 刷新数据
    ElMessage.success("评论已删除");
  } catch (error) {
    ElMessage.error("删除失败: " + error.message);
  }
};

// 删除文章
const deleteArticle = async () => {
  try {
    await api.delete(`/articles/${articleId}`);
    ElMessage.success("文章已删除");
    setTimeout(() => {
      router.push("/");
    }, 1000);
  } catch (error) {
    ElMessage.error("删除失败: " + error.message);
  }
};

// 初始化加载数据
info();
</script>
<style scoped>
.main {
  background-color: #f8f9fa;
  padding: 24px;
}

.main-contan {
  max-width: 1200px;
  margin: 0 auto;
}

.left-card,
.right-card {
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.left-card:hover,
.right-card:hover {
  transform: translateY(-2px);
}

.post-show-card {
  margin-bottom: 16px;
  border-radius: 12px;
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.user-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.username {
  font-size: 16px;
  font-weight: 500;
  color: #1c1e21;
}

.time {
  color: #999;
  font-size: 12px;
  margin-top: 2px;
}
.post-content {
  font-size: 16px;
  line-height: 1.6;
  color: #1c1e21;
  margin-bottom: 16px;
}

.post-tag {
  background-color: #409eff;
  color: #fff;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 14px;
  margin-right: 8px;
}

.post-image {
  width: 33%;
  max-height: 500px;
  border-radius: 12px;
  object-fit: cover;
}

.post-stats {
  padding: 12px 0;
  border-top: 1px solid #e4e7ed;
  color: #606266;
  font-size: 14px;
  display: flex; /* 使用 flex 布局 */
  justify-content: space-between; /* 让子元素分别在左右两端 */
  align-items: center; /* 垂直居中对齐 */
}

.stats-right span:first-child {
  margin-right: 10px;
}

.signature-section {
  display: flex;
  align-items: center;
  margin: 15px 0 10px;
}

.signature-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 15px;
}

.signature-info {
  display: flex;
  flex-direction: column;
}

.signature-username {
  font-size: 16px;
  font-weight: 500;
  color: #222226;
}

.signature-text {
  margin: 0;
  font-size: 14px;
  color: #555666;
}

.edit-signature-btn {
  width: 100%;
  background-color: #e4e7ed;
  border-radius: 5px;
  padding: 5px 10px;
}

.right-section {
  padding: 12px 0;
  border-bottom: 1px solid #e4e7ed;
  font-size: 14px;
  color: #606266;
}

.section-icon {
  margin-right: 8px;
  color: #909399;
}

.post-comment {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.comment-input {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.user-avatar-small {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #e4e7ed;
}

.comment-input-box {
  margin-left: 12px;
}

.comment-list {
  margin-top: 16px;
}

.comment-item {
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 12px;
  background-color: #f8f9fa;
}

.user-avatar-tiny {
  width: 32px;
  height: 32px;
  margin-right: 10px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #e4e7ed;
}

.comment-author {
  font-weight: 500;
  color: #1c1e21;
}

.comment-content {
  margin: 8px 0;
  color: #1c1e21;
}

.comment-meta {
  color: #909399;
  font-size: 12px;
}
</style>

<style scoped>
.three-d-text {
  font-size: 48px;
  font-weight: bold;
  color: #2196f3;
  text-shadow: 1px 1px 0 #1976d2, 2px 2px 0 #1976d2, 3px 3px 0 #1976d2, 4px 4px 0 #1976d2,
    5px 5px 0 #1976d2, 6px 6px 0 #1976d2, 7px 7px 0 #1976d2,
    8px 8px 10px rgba(0, 0, 0, 0.5);
}
</style>
